<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/22 00:21
 */

namespace module\ai\library\channel\completion;

use module\ai\library\channel\abstract\Completion;

class TencentCompletion extends Completion
{
    /**
     * @inheritDoc
     */
    protected function rawToData(): void
    {
        if (isset($data['Response']['Error'])) {
            $this->error($data['Response']['Error']['Message'], $data['Response']['Error']['Code']);
        } else if (isset($data['Response']['Choices'][0])) {
            $choices = $data['Response']['Choices'][0];
            $message = $choices[$this->stream ? 'Delta' : 'Message'];
            $this->data['message']['content'] = $message['Content'];
            $this->data['message']['role'] = $message['Role'];
            $this->data['finish'] = $this->stream
                ? (in_array($choices['FinishReason'] ?? '', ['stop', 'sensitive']) ? 'finish' : 'receiving')
                : 'finish';
            $this->data['finish_reason'] = $choices['FinishReason'] ?? '';
            $this->data['tokens'] = [
                'send_tokens'    => $data['Response']['Usage']['PromptTokens'] ?? 0,
                'receive_tokens' => $data['Response']['Usage']['CompletionTokens'] ?? 0,
                'total_tokens'   => $data['Response']['Usage']['TotalTokens'] ?? 0,
            ];
        }
    }
}